<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html xmlns='http://www.w3.org/1999/xhtml'
        xmlns:v='urn:schemas-microsoft-com:vml'>

<head>
    <meta http-equiv='content-type' content='text/html; charset=UTF-8'/>
    <meta http-equiv='cache-control' content='no-cache'/>
    <meta http-equiv='expires' content='0'/>
    <meta name='copyright' content='Copyright (C) XXX Consultants'/>
    <meta name='robots' content='none'/>


    <link rel="stylesheet" href="/gts/css/main.css"/>

    <link rel="shortcut icon" href="/gts/images/favicon.ico"
            type="image/x-icon"/>

    <title>XXX Tracking System</title>

    <script src='http://maps.google.com/maps?file=api&v=2&key=*** Place Google Maps Key Here *' type="text/javascript">
    </script>

    <script type="text/javascript">
    //<![CDATA[

    var map;


    function createMarker(pt, ed){

    if (window.GMarker) {
    var lat = ed.latitude;
    var lon = ed.longitude;
    var speed = ed.speed;
    var dt = ed.timestamp
    var html = '';
    html += '<table style="width:110">';
    html += '<tr><td align=left nowrap><small>Date: ' +dt+ '</small></td></tr>';
    html += '<tr><td align=left nowrap><small>GPS: ' + lat + ' / ' + lon + '</small></td></tr>';
    html += '<tr><td align=left nowrap><small>Speed: ' + speed + '</small></td></tr>';
    html += '</table>';



    var iconBlue = new GIcon();
    iconBlue.image = 'http://labs.google.com/ridefinder/images/mm_20_blue.png';
    iconBlue.shadow = 'http://labs.google.com/ridefinder/images/mm_20_shadow.png';
    iconBlue.iconSize = new GSize(12, 20);
    iconBlue.shadowSize = new GSize(22, 20);
    iconBlue.iconAnchor = new GPoint(6, 20);
    iconBlue.infoWindowAnchor = new GPoint(5, 1);


    var options = {
    title: "haha1111",
    icon: iconBlue,
    draggable: true,
    bounceGravity: 0.2,
    dragCrossMove: true
    };
    var pin    = new GMarker(pt,options);

    GEvent.addListener(pin, 'click', function() {
    pin.openInfoWindowHtml(html);    });

    return pin;

    }else{
    return null;
    }

    }

    function parseResponse(data){
    map.clearOverlays();
    // alert(data);
    try{
    var events = eval("("+data+")");
    }catch(e){
    alert(e);
    //FIXME return;
    }



    var mapBounds = new GLatLngBounds();

    var markers = [];
    var polylines = [];
    var GLatLngs = [];

    for(eventIndex=0; eventIndex<events.length; eventIndex++){

    var ed = events[eventIndex];
    var lat = ed.latitude;
    var lon = ed.longitude;


    var point = new GLatLng(lat, lon);
    if(eventIndex==0){
    map.setCenter(point ,1);
    }

    mapBounds.extend(point);

    var marker = createMarker(point, ed);

    markers.push(marker);
    GLatLngs.push(point);
    } //end inner for

    var polyline = new GPolyline(GLatLngs,  "#FF0000", 5);

    var centerPt = mapBounds.getCenter();
    var zoomFactor = map.getBoundsZoomLevel(mapBounds);
    zoomFactor = zoomFactor>1?zoomFactor-1:zoomFactor;
    map.setCenter(centerPt, zoomFactor);


    for(markerIndex=0; markerIndex<markers.length; markerIndex++)
    {
    map.addOverlay(markers[markerIndex]);
    }

    map.addOverlay(polyline);

    }


    function load(){
    if (GBrowserIsCompatible()) {
    map = new GMap2(document.getElementById("map"));
    // map.addControl(new GSmallMapControl());
    map.addControl(new GMapTypeControl());
    map.addControl(new GLargeMapControl());
    map.addMapType(G_PHYSICAL_MAP);



    var url =  '/gts/device/trackAjax?id='+ "${device.id}";

    GDownloadUrl(url,
    function(data, responseCode) {
    if(responseCode == 200) {
    parseResponse(data);
    }else{

    }
    }
    );
    map.clearOverlays();
    }
    }


    var geozoneGPolygons = null ;
    var geozoneShown = false;

    function showGeozones(){

    if (GBrowserIsCompatible()) {
    if(geozoneShown){
    for(gpi=0; gpi<geozoneGPolygons.length; gpi++){
    var geozone = geozoneGPolygons[gpi];
    map.removeOverlay(geozone);
    }

    geozoneShown = false;
    }else{
    if(geozoneGPolygons && geozoneGPolygons.length>0){
    for(var gpi=0; gpi<geozoneGPolygons.length; gpi++){
    var geozone = geozoneGPolygons[gpi];
    map.addOverlay(geozone);
    }
    geozoneShown = true;
    }else{
    var url =  '/gts/devicegroup/getGeozonesAjax?id='+"${device.devicegroup.id}";
    GDownloadUrl(url,    function(data, responseCode) {
    if(responseCode == 200) {
    geozoneGPolygons = [];
    parseGeozones(data);
    }else{
    }
    }
    );
    }
    }
    }

    }

    var lineColor = "#0000af";
    var fillColor = "#335599";
    var lineWeight = 3;
    var lineOpacity = .8;
    var fillOpacity = .2;


    function createPgn(points){
    var gp = new GPolygon(points, lineColor, lineWeight, lineOpacity, fillColor, fillOpacity);
    return gp;
    }



    function parseGeozones(myJSONtext){
    try{
    var jsonText = eval("("+myJSONtext+")");
    }catch(e){
    alert(e);
    }

    if(jsonText){

    var len = jsonText.length;
    alert(len);
    for(var i=0;i<len;i++){
    var points = jsonText[i];

    var  zoneType=null;
    var latlons = []
    var isCircle = false;
    var circleIndex = -1;

    for(var pi=0;pi<points.length;pi++){
    var point = points[pi]
    zoneType = point.zoneType;
    var lat = point.latitude;
    var lon = point.longitude;

    if(zoneType=="Circle"){
    isCircle = true;
    if(point.center){
    circleIndex = pi;
    }
    }

    var latlon = new GLatLng(lat,lon);
    latlons.push(latlon);
    }


    var myshape = null;

    if(zoneType=="Triangle")
    {
    latlons.push(latlons[0]);
    myShape =createPgn(latlons);

    }else if(zoneType=="Circle"){

    var center=null;
    var radius=null;

    if(circleIndex==0){
    center = latlons[0];
    radius = latlons[1];
    }else if(circleIndex==1){
    center = latlons[1];
    radius = latlons[0];
    }else{
    }

    if(center){
    var lat = center.lat() ;
    var lng = center.lng() ;

    var meters =  radius.distanceFrom(center,6378137);
    var Cradius = meters  * 0.000621371192 ;
    var Ccolor = '#0000ff' ;        // color blue
    var Cwidth = 3 ;            // width pixels
    var d2r = Math.PI/180 ;        // degrees to radians
    var r2d = 180/Math.PI ;        // radians to degrees
    var Clat = (Cradius/3963) * r2d ;    //  using 3963 as earth's radius
    var Clng = Clat/Math.cos(lat*d2r);

    var Cpoints = [] ;
    //calculate  circle points
    for (var i = 0 ; i < 25 ; i++)
    {
    var theta = Math.PI * (i/12) ;
    Cx = lng + (Clng * Math.cos(theta)) ;
    Cy = lat + (Clat * Math.sin(theta)) ;
    Cpoints.push(new GPoint(Cx,Cy)) ;
    }

    myShape = new GPolyline(Cpoints,Ccolor,Cwidth);
    }



    }else if(zoneType=="Rectangle"){
    var g11 = latlons[0];
    var g22 = latlons[1];
    var lat1 = g11.lat();
    var lat2 = g22.lat();
    var lng1 = g11.lng();
    var lng2 = g22.lng();
    var g12 = new GLatLng(lat1,lng2);
    var g21 = new GLatLng(lat2,lng1);

    var rectpp = [];
    rectpp.push(g11);
    rectpp.push(g12);
    rectpp.push(g22);
    rectpp.push(g21);
    rectpp.push(g11);

    myShape =createPgn(rectpp);

    if(myShape){
    map.addOverlay(myShape);
    geozoneGPolygons.push(myShape);
    }

    }else if(zoneType=="Polygon"){
    latlons.push(latlons[0]);


    var myShape =createPgn(latlons);
    map.addOverlay(myShape);
    geozoneGPolygons.push(myShape);
    }

    if(myShape){
    map.addOverlay(myShape);
    geozoneGPolygons.push(myShape);
    }
    }
    
    geozoneShown = true;

    return 1;
    }else{
    return 0;
    }
    }


    var recursive = 0;

    function update_map(){
    if(recursive==0){
    recursive++
    var df =new Date(document.getElementById("datefrom_year").value, document.getElementById("datefrom_month").value-1 ,document.getElementById("datefrom_day").value-1 );
    var dt =new Date(document.getElementById("dateto_year").value, document.getElementById("dateto_month").value ,document.getElementById("dateto_day").value );
    var url =  '/gts/device/trackAjax?id='+ "${device.id}&df="+df.getTime()+"&dt="+dt.getTime();
    GDownloadUrl(url,function(data, responseCode) {
    if(responseCode == 200) {
    parseResponse(data);
    }else{    }
    });
    map.clearOverlays();
    recursive--}
    }


    //]]>
    </script>

</head>

<body onload="load();" onunload="GUnload()">

<div id="spinner" class="spinner" style="display: none;"><img
        src="/gts/images/spinner.gif" alt="Spinner"/></div>
<div class="logo"><img src="/gts/images/grails_logo.jpg"
        alt="Grails"/></div>

<div class="nav"><span class="menuButton"><a class="home"
        href="${createLinkTo(dir: '')}">Home</a></span> <span class="menuButton"><g:link
        controller="device" class="list" acti n="list">Device List</g:link></span> <span
        class="menuButton"><g:link class="create" controller="device"
        action="create">New Device</g:link></span></div>


<h1>Show Device</h1>



<g:if test="${flash.message}">
    <div class="message">${flash.message}</div>
</g:if>



<div id="device_block" style="float:left;">
    <ul style="float:left;">
        <li>Id:</li>
        <li>Allow Notify:</li>

        <li>Devicegroup:</li>

        <li>Equipment Type:</li>

        <li>Imei Number:</li>

        <li>Is Active:</li>

        <li>Last Input State:</li>

        <li>Last Updated:</li>

        <li>Notes:</li>

        <li>Notify Action:</li>

        <li>Notify Email:</li>

        <li>Sim Phone Number:</li>
    </ul>

    <ul style="float:left;list-style:none;">
        <li><span id="deviceid">${device.id}</span></li>

        <li>${device.allowNotify}</li>

        <li><g:link controller="track" action="trackgroup"
                id="${device?.devicegroup?.id}">${device?.devicegroup} Map</g:link></li>

        <li>${device.equipmentType}</li>

        <li>${device.imeiNumber}</li>


        <li>${device.isActive}</li>

        <li>${device.lastInputState}</li>

        <li>${device.lastUpdated}</li>

        <li>${device.notes}</li>

        <li>${device.notifyAction}</li>

        <li>${device.notifyEmail}</li>

        <li>${device.simPhoneNumber}</li>
    </ul>

</div>



<div id="map_block" style="float:left;">
    <div id='map' style='position: relative; width: 680px; height: 420px;'></div>
    <div>
        <ul sytle="list-style:none">
            <li>DateFrom : <g:datePicker name="datefrom" value="${new Date()-1}" precision="day" years="${2000..2010}"/></li>
            <li>DateTo: <g:datePicker name="dateto" value="${new Date()}" precision="day" years="${2000..2010}"/></li>
            <input type="submit" name="update_map" value="update_map" onclick="update_map();"/>
        </ul>
    </div>
</div>

<div>
    Location Details(<a href='javascript:mapProviderToggleDetails()'>toggle show</a>)
    <div id='trackMapDataTable' style='margin-left: 15px;'></div>
</div>



<div id="geozones">
    <g:if test="${device.devicegroup.geozones}">
        <a href='javascript:showGeozones()'>toggle Geozones</a>
    </g:if></div>

<div id="responseJson"></div>

</body>
</html>